package org.annoflow.aspect;

import java.util.HashMap;

import org.annoflow.policy.Policy;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.PolicyType;
import org.aspectj.lang.reflect.InitializerSignature;

public aspect PolicyAspect {
	private static HashMap<Class<? extends PolicyType>, PolicyType> _instances = 
											new HashMap<Class<? extends PolicyType>, PolicyType>();
	
	pointcut classInit(Policy p) : 
		staticinitialization(@Policy *)
		&& @annotation(p);
	
	after(Policy p) : classInit(p){
		InitializerSignature initsig =
			(InitializerSignature)thisJoinPointStaticPart.getSignature();
		Class<?> clazz = initsig.getDeclaringType();
		
		try {
			PolicyType pt = _instances.get(p.value());
			if (pt == null) {
				synchronized(_instances) {
					if(!_instances.containsKey(p.value()))
						_instances.put(p.value(), p.value().newInstance());
				}
				pt = _instances.get(p.value());
			}
			PolicyManager.addClassPolicy(clazz, pt);
		} catch (InstantiationException e) {
			//Do nothing
		} catch (IllegalAccessException e) {
			//Do nothing
		}
	}
}
